package com.clothing.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.clothing.dao.ArticleDao;
import com.clothing.dao.ArticlePraiseDao;
import com.clothing.entity.Article;
import com.clothing.entity.ArticlePraise;
import com.clothing.entity.User;
import com.clothing.service.ArticlePraiseService;
import com.clothing.utils.Utils;
import com.clothing.utils.page.Filter;


/**
 * @ClassName: ArticlePraiseServiceImpl 
 * @Description: TODO(ArticlePraise-ServiceImpl)
 * @author Charles
 * @date 2018年6月8日
 * @version 1.0
 */
@Service
public class ArticlePraiseServiceImpl extends
        BaseServiceImpl<ArticlePraise, Long> implements ArticlePraiseService
{
    @Autowired
    private ArticlePraiseDao articlePraiseDao;
    
    @Autowired
    private ArticleDao articleDao;
    
    @Override
    public void praise(Article article, User user)
    {
        ArticlePraise articlePraise = findOne(article.getId(), user.getId());
        if (null == articlePraise)
        {
            articlePraise = new ArticlePraise();
            articlePraise.setArticle(article);
            articlePraise.setUser(user);
            articlePraise.setPraise(Boolean.TRUE);
            articlePraiseDao.persist(articlePraise);
            article.setPraiseQuantity(article.getPraiseQuantity() + 1);
        }
        else
        {
            if (articlePraise.getPraise())
            {
                articlePraise.setPraise(Boolean.FALSE);
                article.setPraiseQuantity(article.getPraiseQuantity() - 1);
            }
            else
            {
                articlePraise.setPraise(Boolean.TRUE);
                article.setPraiseQuantity(article.getPraiseQuantity() + 1);
            }
            
            articlePraiseDao.merge(articlePraise);
        }
        articleDao.merge(article);
    }

    @Override
    @Transactional(readOnly = true)
    public ArticlePraise findOne(Long articleId, Long userId)
    {
        List<Filter> filters = new ArrayList<>();
        filters.add(Filter.eq("article.id", articleId));
        filters.add(Filter.eq("user.id", userId));
        List<ArticlePraise> articlePraises = findList(1, filters, null);
        if (Utils.isEmpty(articlePraises))
        {
            return null;
        }
        return articlePraises.get(0);
    }
}
